import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hiot_cloud_app_v1/app/constants/enums/device_type.dart';
import 'package:hiot_cloud_app_v1/app/core/base/base_controller.dart';
import 'package:hiot_cloud_app_v1/app/data/models/device_model.dart';
import 'package:hiot_cloud_app_v1/app/data/providers/device_provider.dart';
import 'package:hiot_cloud_app_v1/app/routes/app_routes.dart';

class DeviceListController extends BaseController {
  final DeviceProvider _deviceProvider = Get.find<DeviceProvider>();

  // 设备列表
  final RxList<DeviceModel> devices = <DeviceModel>[].obs;
  
  // 过滤后的设备列表
  final RxList<DeviceModel> filteredDevices = <DeviceModel>[].obs;
  
  // 设备分组
  final RxList<String> deviceGroups = <String>['全部', '默认分组', '客厅', '卧室', '厨房', '浴室'].obs;
  final RxString selectedGroup = '全部'.obs;
  
  // 搜索关键词
  final RxString searchQuery = ''.obs;
  
  // 错误信息
  final RxString errorMessage = ''.obs;

  @override
  void onInit() {
    super.onInit();
    loadDevices();
  }

  /// 加载设备列表
  Future<void> loadDevices() async {
    try {
      showLoading();
      errorMessage.value = '';
      
      // 模拟从API获取设备列表
      await Future.delayed(const Duration(seconds: 2));
      
      // 模拟设备数据
      devices.value = [
        DeviceModel(
          id: 'dev001',
          name: '客厅灯',
          type: DeviceType.lightingController,
          status: DeviceStatus.online,
          createdAt: DateTime.now(),
          lastUpdatedAt: DateTime.now(),
          ownerId: 'user001',
          isEnabled: true,
          isShared: false,
          location: '客厅',
          description: '飞利浦智能灯泡',
        ),
        DeviceModel(
          id: 'dev002',
          name: '卧室灯',
          type: DeviceType.lightingController,
          status: DeviceStatus.offline,
          createdAt: DateTime.now(),
          lastUpdatedAt: DateTime.now(),
          ownerId: 'user001',
          isEnabled: true,
          isShared: false,
          location: '卧室',
          description: '小米智能灯带',
        ),
        DeviceModel(
          id: 'dev003',
          name: '温湿度传感器',
          type: DeviceType.temperatureSensor,
          status: DeviceStatus.online,
          createdAt: DateTime.now(),
          lastUpdatedAt: DateTime.now(),
          ownerId: 'user001',
          isEnabled: true,
          isShared: false,
          location: '客厅',
          description: '小米温湿度传感器',
        ),
        DeviceModel(
          id: 'dev004',
          name: '智能插座',
          type: DeviceType.switchController,
          status: DeviceStatus.online,
          createdAt: DateTime.now(),
          lastUpdatedAt: DateTime.now(),
          ownerId: 'user001',
          isEnabled: true,
          isShared: false,
          location: '厨房',
          description: '智能插座',
        ),
        DeviceModel(
          id: 'dev005',
          name: '网关',
          type: DeviceType.gateway,
          status: DeviceStatus.online,
          createdAt: DateTime.now(),
          lastUpdatedAt: DateTime.now(),
          ownerId: 'user001',
          isEnabled: true,
          isShared: false,
          location: '客厅',
          description: '智能家居网关',
        ),
      ];
      
      _applyFilters();
      hideLoading();
    } catch (e) {
      hideLoading();
      errorMessage.value = e.toString();
      showError('加载设备列表失败: ${e.toString()}');
    }
  }

  /// 刷新设备列表
  Future<void> refreshDevices() async {
    return loadDevices();
  }

  /// 选择设备分组
  void selectGroup(String group) {
    selectedGroup.value = group;
    _applyFilters();
  }

  /// 搜索设备
  void searchDevices(String query) {
    searchQuery.value = query;
    _applyFilters();
  }

  /// 应用过滤器
  void _applyFilters() {
    List<DeviceModel> result = devices;
    
    // 按分组过滤
    if (selectedGroup.value != '全部') {
      result = result.where((device) => device.location == selectedGroup.value).toList();
    }
    
    // 按搜索关键词过滤
    if (searchQuery.isNotEmpty) {
      final String query = searchQuery.value.toLowerCase();
      result = result.where((device) =>
        device.name.toLowerCase().contains(query) ||
        device.id.toLowerCase().contains(query) ||
        device.type.toReadableString().toLowerCase().contains(query)
      ).toList();
    }
    
    filteredDevices.value = result;
  }

  /// 打开设备详情
  void openDeviceDetail(DeviceModel device) {
    Get.toNamed('${AppRoutes.deviceDetail}/${device.id}');
  }

  /// 打开设备设置
  void openDeviceSettings(DeviceModel device) {
    Get.toNamed('${AppRoutes.deviceSettings}/${device.id}');
  }

  /// 打开设备数据
  void openDeviceData(DeviceModel device) {
    Get.toNamed('${AppRoutes.deviceData}/${device.id}');
  }

  /// 切换设备状态
  void toggleDevice(DeviceModel device) async {
    try {
      showLoading(message: '正在${device.status == DeviceStatus.online ? '关闭' : '开启'}设备...');
      
      // 模拟API调用
      await Future.delayed(const Duration(seconds: 1));
      
      // 更新设备状态
      final index = devices.indexWhere((d) => d.id == device.id);
      if (index != -1) {
        final updatedDevice = devices[index].copyWith(
          status: device.status == DeviceStatus.online
              ? DeviceStatus.offline
              : DeviceStatus.online,
        );
        
        devices[index] = updatedDevice;
        
        // 更新过滤后的设备列表
        final filteredIndex = filteredDevices.indexWhere((d) => d.id == device.id);
        if (filteredIndex != -1) {
          filteredDevices[filteredIndex] = updatedDevice;
        }
      }
      
      hideLoading();
      final status = device.status == DeviceStatus.online ? '已关闭' : '已开启';
      showSuccess('设备${status}');
    } catch (e) {
      hideLoading();
      showError('操作失败: ${e.toString()}');
    }
  }
  
  /// 删除设备
  void deleteDevice(DeviceModel device) {
    Get.dialog(
      AlertDialog(
        title: const Text('删除设备'),
        content: const Text('确定要删除该设备吗？此操作无法撤销。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Get.back();
              try {
                showLoading(message: '正在删除设备...');
                
                // 模拟API调用
                await Future.delayed(const Duration(seconds: 1));
                
                devices.removeWhere((d) => d.id == device.id);
                filteredDevices.removeWhere((d) => d.id == device.id);
                
                hideLoading();
                showSuccess('设备已删除');
              } catch (e) {
                hideLoading();
                showError('删除失败: ${e.toString()}');
              }
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
} 